package com.goddess.yeecolor.activity;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.goddess.yeecolor.R;
import com.goddess.yeecolor.base.BaseActivity;
import com.goddess.yeecolor.interfaceAll.OnPermissionRequestListener;
import com.goddess.yeecolor.tools.Constans;
import com.goddess.yeecolor.tools.ImageUtils;
import com.goddess.yeecolor.tools.JumpIntents;
import com.goddess.yeecolor.tools.LogUtils;
import com.goddess.yeecolor.tools.MyUrl;
import com.goddess.yeecolor.tools.OkttpUtils;
import com.goddess.yeecolor.tools.PublicUtils;
import com.goddess.yeecolor.tools.SharePreceUtils;
import com.goddess.yeecolor.tools.ToastUtils;
import com.goddess.yeecolor.view.CircleImageView;
import com.goddess.yeecolor.view.PopPopuWindowUtils;
import com.goddess.yeecolor.view.dialog_progress;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 完善个人资料
 */
public class PerfectMeansAcitivity extends BaseActivity implements View.OnClickListener {

    private int Tag = 1;
    private int Tag1 = 2;
    private Map<Object, Object> map;
    private CircleImageView perfectmeans_image;
    private PopPopuWindowUtils popuWindowUtils;
    private View mView;
    private TextView mTitle;
    private Toolbar mToobar;
    private Bundle bundle;
    private ImageView perfectmeans_touxiang, perfectmeans_selectTrade, perfectmeans_selectprofession;//行业,职业
    private Button perfectmeans_save;
    private EditText perfectmeans_wx, perfectmeans_company, perfectmeans_city, perfectmeans_nick;
    private String imageUrl = "";
    private TextView perfectmeans_trade, perfectmeans_profession;
    private String tag;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);
        mView = LayoutInflater.from(this).inflate(R.layout.activity_perfectmeans, null);
        setContentView(mView);
        tag = getIntent().getStringExtra("tag");
//        if (!hasPermissin(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//            requestPermission(Constans.WRIGTE_CALL_EXTERNAL_CODE, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
//        }
        initFindView();
        initData();
        initOnClck();
    }

    private com.goddess.yeecolor.view.dialog_progress dialog_progress;

    private void setProgress() {
        dialog_progress = new dialog_progress(this);
        dialog_progress.requestWindowFeature(Window.FEATURE_NO_TITLE);

        dialog_progress.setCanceledOnTouchOutside(false);//按返回键可以关闭进度条
        dialog_progress.show();
    }

    @Override
    public void initOnClck() {
        perfectmeans_save.setOnClickListener(this);
        perfectmeans_image.setOnClickListener(this);
        perfectmeans_trade.setOnClickListener(this);
        perfectmeans_profession.setOnClickListener(this);
    }

    @Override
    public void initFindView() {
        mToobar = (Toolbar) findViewById(R.id.title_toobar);
        mTitle = (TextView) findViewById(R.id.title_content);
        mTitle.setText("个人资料");
        mToobar.setNavigationIcon(R.mipmap.back3x);
        mToobar.setNavigationOnClickListener((view) -> {
            setFiish(this);
        });
        perfectmeans_image = (CircleImageView) findViewById(R.id.perfectmeans_image);
        perfectmeans_touxiang = (ImageView) findViewById(R.id.perfectmeans_touxiang);
        perfectmeans_selectTrade = (ImageView) findViewById(R.id.perfectmeans_selectTrade);
        perfectmeans_selectprofession = (ImageView) findViewById(R.id.perfectmeans_selectprofession);
        perfectmeans_wx = (EditText) findViewById(R.id.perfectmeans_wx);
        perfectmeans_nick = (EditText) findViewById(R.id.perfectmeans_nick);
        perfectmeans_trade = (TextView) findViewById(R.id.perfectmeans_trade);
        perfectmeans_profession = (TextView) findViewById(R.id.perfectmeans_profession);
        perfectmeans_company = (EditText) findViewById(R.id.perfectmeans_companys);
        perfectmeans_city = (EditText) findViewById(R.id.perfectmeans_city);
        perfectmeans_save = (Button) findViewById(R.id.perfectmeans_save);

        //弹窗
        OnClickLintener onClickLintener = new OnClickLintener();
        //弹窗
        popuWindowUtils = new PopPopuWindowUtils(this, onClickLintener, "拍一张", "从相册中选一张", 0);
    }

    @Override
    public void initData() {
        if (tag.equals("设置个人资料")) {//修改
            unique = SharePreceUtils.getOther("user", "unique");
            imageUrl = SharePreceUtils.getOther("user", "thumb");
            ImageUtils.getInstance().ImageStart(this, imageUrl, perfectmeans_image);
            perfectmeans_nick.setText(SharePreceUtils.getOther("user", "nickname"));
            perfectmeans_wx.setText(SharePreceUtils.getOther("user", "weixinid"));
            perfectmeans_trade.setText(SharePreceUtils.getOther("user", "industry"));
            perfectmeans_profession.setText(SharePreceUtils.getOther("user", "occupation"));
            perfectmeans_company.setText(SharePreceUtils.getOther("user", "company"));
            perfectmeans_city.setText(SharePreceUtils.getOther("user", "city"));

        } else if (tag.equals("完善个人资料")) {//注册
            unique = SharePreceUtils.getOther("righter", "unique");

        }
    }

    private String unique, thumb, nickname, weixinid, industry, occupation, company, city, nick;

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.perfectmeans_image://头像
                popuWindowUtils.showAsDropDown(mToobar, Gravity.CENTER, 0, 0);
                break;
            case R.id.perfectmeans_trade://行业

                bundle = new Bundle();
                bundle.putString("Tag", "行业");
                JumpIntents.startIntentResultIntent(this, ProfessionTradeActivity.class, Tag, bundle);

                break;
            case R.id.perfectmeans_profession://职业
                bundle = new Bundle();
                bundle.putString("Tag", "职业");
                JumpIntents.startIntentResultIntent(this, ProfessionTradeActivity.class, Tag, bundle);
                break;
            case R.id.perfectmeans_save://保存

                nickname = perfectmeans_nick.getText().toString().trim() + "";
                weixinid = perfectmeans_wx.getText().toString().trim() + "";
                industry = perfectmeans_trade.getText().toString().trim() + "";
                occupation = perfectmeans_profession.getText().toString().trim() + "";
                company = perfectmeans_company.getText().toString().trim() + "";
                city = perfectmeans_city.getText().toString().trim() + "";
                /**
                 * unique  用户标示
                 * thumb  头像地址
                 * nickname  昵称
                 * weixinid 微信id
                 * industry  行业
                 * occupation 职业
                 * company 公司
                 * city  城市
                 */
                map = new HashMap<>();
                map.put("unique", unique);
                map.put("thumb", imageUrl);
                map.put("nickname", nickname);
                map.put("weixinid", weixinid);
                map.put("industry", industry);
                map.put("occupation", occupation);
                map.put("company", company);
                map.put("city", city);
                setProgress();
                OkttpUtils.getIntence().OkttpPost(MyUrl.url + MyUrl.basic, map, handler, 1);
                break;
        }
    }

    /**
     * popuwindow的弹框
     */
    //调用系统相册-选择图片
    private static final int IMAGE = 1;
    public static final int CROP_PHOTO = 2;
    private Intent intent;
    private String cameraUrl;

    private final int PERMISSION_CAMERA = 1;
    private final int PERMISSION_ALBUM = 2;

    class OnClickLintener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.popuwindow_examine://相机
                    popuWindowUtils.dismiss();
                    PublicUtils.getCameraPermission(PerfectMeansAcitivity.this, PERMISSION_CAMERA, new OnPermissionRequestListener() {
                        @Override
                        public void onSuccess() {
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(intent, 100);
//
                        }
                    });
                    break;
                case R.id.popuwindow_cancalenroll://相册
                    popuWindowUtils.dismiss();
                    PublicUtils.getWriteExternalStoragePermission(PerfectMeansAcitivity.this, PERMISSION_ALBUM, new OnPermissionRequestListener() {
                        @Override
                        public void onSuccess() {
                            PublicUtils.openAlbumActivity(200, PerfectMeansAcitivity.this);
                        }
                    });
                    break;
                case R.id.popuwindow_cancal://取消
                    if (popuWindowUtils != null) {
                        popuWindowUtils.dismiss();
                    }
                    break;
            }
        }
    }


    private File mFile;
    private String name;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
            switch (requestCode) {
                case 100:
                    //上传
                    Bundle bundle = data.getExtras();
                    if (bundle != null) {
                        Bitmap  photo = (Bitmap) bundle.get("data"); //get bitmap
                        //spath :生成图片取个名字和路径包含类型
                        SaveImage(photo);
                    } else {
                        Toast.makeText(this, "err****", Toast.LENGTH_LONG).show();
                        return;
                    }
//                        setProgress();
//                        map = new HashMap<>();
//                        map.put("filedata", cameraUrl);
//                        Log.i("zy", cameraUrl + "图片");
//                        OkttpUtils.getIntence().OkttpPost(MyUrl.touxiang, handler, map, 2);
                    break;
                case 200:
                    if (data!=null){
                        String originPath = PublicUtils.getOriginPathWithAlbum(data, this);
                        //上传
                        setProgress();
                        map = new HashMap<>();
                        map.put("filedata", originPath);
                        OkttpUtils.getIntence().OkttpPost(MyUrl.touxiang, handler, map, 2);
                    }
                    break;
                case 1:
                    if (resultCode == 2) {//行业
                        name = data.getStringExtra("name");
                        perfectmeans_trade.setText(name);
                    } else if (resultCode == 3) {
                        name = data.getStringExtra("name");
                        perfectmeans_profession.setText(name);
                    }
                    break;
            }
    }

    //保存图片
    private Bitmap mHeadBitmap;
    private File file;

    private void SaveImage(Bitmap bitmap) {

        File files = new File(Environment.getExternalStorageDirectory(), "Goddess");
        if (!files.exists()) {
            files.mkdirs();
        }
        String fileName = System.currentTimeMillis() + ".png";
        file = new File(files, fileName);
        try {
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);

            out.close();
            perfectmeans_image.setImageBitmap(bitmap);//显示图片
            Glide.with(this).load(file).into(perfectmeans_image);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
        path = file.getAbsolutePath();
        //上传
        setProgress();
        Map<Object, Object> map = new HashMap<>();
        map.put("filedata", path);
        OkttpUtils.getIntence().OkttpPost(MyUrl.touxiang, handler, map, 2);
    }

    private String path;


    /**
     * 保存
     */
    private String jsonString;
    private int code;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                jsonString = msg.getData().getString("result");
                JSONObject object = new JSONObject(jsonString);
                String msgs = object.getString("msg");
                code = object.getInt("code");
                if (msg.what == 2) {
                    if (code == 100) {
                        JSONObject result = object.getJSONObject("result");
                        imageUrl = result.getString("remote");

                        ImageUtils.getInstance().ImageStart(PerfectMeansAcitivity.this, imageUrl, perfectmeans_image);
                    } else if (code == 403) {
                        ToastUtils.toast(msgs);
                    }

                } else if (msg.what == 1) {
                    if (code == 100) {
                        ToastUtils.toast(msgs);
                        JSONObject result = object.getJSONObject("result");

                        SharePreceUtils.saveData(result.getString("unique"), result.getString("thumb"), result.getString("nickname"), result.getString("weixinid"), result.getString("industry")
                                , result.getString("occupation"), result.getString("company"), result.getString("city"), "", true, "");
                        if (tag.equals("设置个人资料")) {
                            setFiish(PerfectMeansAcitivity.this);
                        } else if (tag.equals("完善个人资料")) {
                            SharePreceUtils.clearData("user");//清空
                            JumpIntents.startIntent(PerfectMeansAcitivity.this, LoginAcitivity.class);
                            finish();
                        }
                    } else if (code == 403) {
                        ToastUtils.toast(msgs);
                    }
                }
                if (dialog_progress != null && dialog_progress.isShowing()) {
                    dialog_progress.dismiss();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog_progress != null && dialog_progress.isShowing()) {
            dialog_progress.dismiss();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    cameraUrl = PublicUtils.getCameraUri();
                    PublicUtils.openCameraActivity(200, cameraUrl, PerfectMeansAcitivity.this);
                } else {
                    Toast.makeText(PerfectMeansAcitivity.this, "没有权限", Toast.LENGTH_SHORT).show();
                }
                break;
            case PERMISSION_ALBUM:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    PublicUtils.openAlbumActivity(200, PerfectMeansAcitivity.this);
                } else {
                    Toast.makeText(PerfectMeansAcitivity.this, "没有权限", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}
